﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace Server
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    class WCFServer : IMessage
    {
        private static List<IMessageCallback> subscribers = new List<IMessageCallback>();
        public ServiceHost host = null;
        public NetTcpBinding tcpbinding = new NetTcpBinding();

        string _port;
        string _host;
        string _login;

        public void Connect()
        {
            ParserXML config = new ParserXML();

            config.LoadXML();
            this._host = config.Ip;
            this._port = config.Port.ToString();

            using (ServiceHost host = new ServiceHost(typeof(WCFServer), new Uri("net.tcp://"+_host+":"+_port)))
            {
                //ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                //behavior.HttpGetEnabled = true;
                //host.Description.Behaviors.Add(behavior);

                tcpbinding.Security.Mode = SecurityMode.None;

                //host.AddServiceEndpoint(typeof(IMetadataExchange), tcpb, new Uri("net.tcp://192.168.1.2:8000/mex"));

                host.AddServiceEndpoint(typeof(IMessage), tcpbinding, "ISubscribe");


                try
                {
                    host.Open();
                    Console.WriteLine("Сервер успешно запущен. Порт 8000.");
                    Console.ReadLine();
                    host.Close();
                }
                catch (Exception e)
                {

                    Console.WriteLine(e.Message);
                }

            }
        }



        public bool Subscribe()
        {
            try
            {
                // получаем хеш-код подключенного клиента
                IMessageCallback callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>();
                if (!subscribers.Contains(callback))
                    subscribers.Add(callback);
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
        }

        public bool Unsubscribe()
        {
            try
            {
                IMessageCallback callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>();
                if (subscribers.Contains(callback))
                    subscribers.Remove(callback);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public void AddMessage(String message)
        {
            //проходим по списку соединений
            subscribers.ForEach(delegate(IMessageCallback callback)
            {
                if (((ICommunicationObject)callback).State == CommunicationState.Opened)
                {
                    Console.WriteLine("Calling OnMessageAdded on callback ({0}).", callback.GetHashCode());
                    callback.OnMessageAdded(message, DateTime.Now);
                }
                else
                {
                    subscribers.Remove(callback);
                }
            });

        }
    }
}
